const TOOLBAR = [{
	content: "申请",
	icon: "el-icon-document-remove",
	type: "primary"
}, ];
const discountFormRules = {
	customerId: [{
		required: true,
		message: '请选择客户公司名称',
		trigger: 'blur'
	}],
	type: [{
		required: true,
		message: '请选择优惠类型',
		trigger: 'blur'
	}],
	applicantId: [{
		required: true,
		message: '请选择申请人',
		trigger: 'blur'
	}],
	leaderId: [{
		required: true,
		message: '请选择主管',
		trigger: 'blur'
	}],
	managerId: [{
		required: true,
		message: '请选择经理',
		trigger: 'blur'
	}],
	preferentialDescription: [{
		required: true,
		message: '请输入优惠描述',
		trigger: 'blur'
	}]
};
const serviceFormDetailRules = {
	name: [{
		required: true,
		message: '请选择服务名称',
		trigger: 'blur'
	}],
	amount: [
	    {required: true, message: '请输入数量', trigger: 'blur'},
		constIntRule
	],
	priceb: [
	    {required: true, message: '请输入优惠前金额', trigger: 'blur'},
		constIntRule
	],
	pricea: [
	    {required: true, message: '请输入优惠后金额', trigger: 'blur'},
		constIntRule
	]
}
const COLUMNS = [
    {
		prop: "id",
		label: "单号",
		width: "80"
	},
    {
		prop: "createTime",
		label: "创建时间",
		width: "120"
	},
	{
		prop: "applicant",
		label: "申请人",
		width: "80"
	},
	{
		prop: "compname",
		label: "客户名称",
		width: "120"
	},
	{
		prop: "leaderstatus",
		label: "主管",
		width: "120"
	},
	{
		prop: "managerstatus",
		label: "经理",
		width: "120"
	},
	{
		prop: "type",
		label: "优惠类型",
		width: "120"
	},
	{
		prop: "status",
		label: "状态",
		width: "80"
	},
	{
		prop: "preferentialDescription",
		label: "优惠描述",
		width: "200"
	},
	{
		prop: "enddate",
		label: "过期日期",
		width: "120"
	}
];

let app = new Vue({
	el: "#app",
	data() {
		return {
			statusoptions: STATUSTYPE,
			headers: {
				Token: localStorage.getItem('TOKEN'),
				UserID: localStorage.getItem('USERID')
			},
			discountForm: {
				applicant: "",
				applicantId: localStorage.getItem('USERID'),
				customerId: null,
				id: null,
				leader: "",
				leaderId: null,
				leaderstatus: "",
				manager: "",
				managerId: null,
				managerstatus: "",
				preferentialDescription: "",
				status: "",
				type: "",
				recs: []
			},
			dialogFormVisible: false,
			submitEditDisable: false,
			imgdialogVisible: false,
			servicescolums: [{
					"prop": "id",
					"label": "编号",
					"width": "50"
				},
				{
					"prop": "name",
					"label": "名称",
					"width": "100"
				},
				{
					"prop": "spec",
					"label": "规格",
					"width": "80"
				},
				{
					"prop": "type",
					"label": "类别",
					"width": "80"
				},
				{
					"prop": "amount",
					"label": "数量",
					"width": "50"
				},
				{
					"prop": "unit",
					"label": "单位",
					"width": "50"
				},
				{
					"prop": "price",
					"label": "单价",
					"width": "100"
				},
				{
					"prop": "priceb",
					"label": "优惠前金额",
					"width": "100"
				},
				{
					"prop": "pricea",
					"label": "优惠后金额",
					"width": "100"
				},
				{
					"prop": "items",
					"label": "服务项目",
					"width": "50"
				},
				{
					"prop": "memo",
					"label": "备注",
					"width": "50"
				}
			],

			detailcolums: [{
					"prop": "id",
					"label": "编号",
					"width": "100"
				},
				{
					"prop": "name",
					"label": "名称",
					"width": "100"
				},
				{
					"prop": "spec",
					"label": "规格",
					"width": "80"
				},
				{
					"prop": "type",
					"label": "类别",
					"width": "80"
				},
				{
					"prop": "unit",
					"label": "单位",
					"width": "50"
				},

				{
					"prop": "price",
					"label": "单价",
					"width": "100"
				},
								{
					"prop": "totalprice",
					"label": "收款金额",
					"width": "100"
				},
				{
					"prop": "items",
					"label": "服务项目",
					"width": "80"
				},
				{
					"prop": "memo",
					"label": "备注",
					"width": "80"
				}
			],
			combinationForm: {
				defaultProps: {
					children: 'children',
					label: 'label'
				},

			},
			stateoptions: STATETYPE,
			teamLink: "i am copy",
			leftbar_show: true,
			// 添加、编辑标识
			action: "",
			dialogEditFormVisible: false,
			dialogItemFormVisible: false,
			tableHeight: window.innerHeight - 180,
			toolbar: TOOLBAR,
			tablecolums: COLUMNS,
			queryForm: {
				applicantId:null,
				status:"",
				delFlag:"未作废",
				endTime: [],
				createTime: [],
				updateTime: [],
				pageNo: 1, // 当前页码
				pagesize: 100, // 每页记录数
				pagesizes: [10, 20, 50, 100]
			},
			serviceForm: {
				id: null,
				mycustomerid: null,
				customerid: null,
				compname: "",
				legalperson: "",
				contacter: "",
				phone: "",
				address: "",
				area: "",
				status: "",
				business: "",
				collectiondate: "",
				transdate: "",
				treasurer: "",
				supervisor: "",
				sellerid: "",
				sellername: "",
				outformerid: "",
				outformername: "",
				src: "",
				signtype: "",
				addresstype: "",
				invoicingtype: "",
				amountinvoicing: "",
				taxtype: "",
				gifts: "",
				paytype: "",
				service: [],
				amounttotal: 0,
				amountreceivables: "",
				amountpayin: "",
				amountend: "",
				amountendcondition: "",
				financeid: "",
				financename: "",
				financestatus: "",
				materials: [],
				annex: [],
				handoverid: "",
				handovername: "",
				handoverstatus: "",
				receiverid: "",
				receivername: "",
				receiverstatus: "",
				supervisorid: "",
				supervisorname: "",
				supervisorstatus: "",
				costerid: "",
				costername: "",
				costerstatus: "",
				memo: ""
			},
			serviceFormDetail: {
				id: 0,
				serviceId: 0,
				name: "",
				spec: "",
				type: "",
				amount: 0,
				unit: "",
				priceb: 0,
				price: 0,
				pricea: 0,
				memo: "",
				service: []
			},
			serviceFormOrg: [],
			//服务项目列表
			services: [],
			pagepersontotal: 0,
			pagepersontotaltemp: 0,
			pagetotal: 0,
			pagetotaltemp: 0,
			pickerOptions: {
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近一个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近三个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
						picker.$emit('pick', [start, end]);
					}
				}]
			},
			dialogserviceFormDetailVisible: false,
			//dialog disabled
			dialogDisabled: true,
			//dialog tab
			tabvalue: "base",
			//公司名
			companys: [],
			//税务类型
			taxtypeoptions: TAXTYPEOPTIONS,
			//状态
			status: WORKORDERSTATUS,
			// 所有用户
			users: [],
			//员工
			members: [],
			//服务名称
			servicenames: [],
			//待办事项
			handleitems: [],
			// 多选
			multipleSelection: [],
			pagedatatemp: [], // 当前页结果集
			pagedata: [], // 当前页结果集
			pagepersondatatemp: [], // 当前页用户结果集
			pagepersondata: [], // 当前页用户结果集
			loaded: false,
			submitDisable: false,
			types:["普通","首单特惠"]
		}
	},
	methods: {
		// 取得所有用户列表
		async getAllUser() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/user/all');
				if (res.code === 200) {
					this.users = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('取得所有用户列表请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();

		},
		// 取得我的客户所有公司列表
		async getCompany() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/mycustomercompany/' + localStorage.getItem('USERID'));
				if (res.code === 200) {
					this.companys = res.data
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('取得我的客户名称请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();

		},
		async initServiceName() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/service/servicename');
				if (res.code === 200) {
					console.log(res)
					this.servicenames = res.data;
					if (this.servicenames.length > 0) {

					}
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},

		toolAction(acName) {
			if (acName == "申请") {
				this.apply()
			} else if (acName == "") {}
		},
		apply() {
			console.log(this.discountForm)
			this.action = "apply"
			this.dialogFormVisible = true
			this.dialogDisabled = false
			this.discountForm.applicant = ""
			this.discountForm.applicantId = null
			this.discountForm.customerId=null,
			this.discountForm.id = null
			this.discountForm.leader = ""
			this.discountForm.leaderId = null
			this.discountForm.leaderstatus = ""
			this.discountForm.manager = ""
			this.discountForm.managerId = null
			this.discountForm.managerstatus = ""
			this.discountForm.preferentialDescription = ""
			this.discountForm.type = "普通"
			this.discountForm.status = ""
			this.discountForm.recs = []
			this.serviceForm.service= []
		},
		//申请确认
		async applyconfirm() {
			
			this.$refs.discountForm.validate(async valid => {
				if (valid) {
					isfirst = true;
					// 检查是否是第一单
					try {
						let res = await axios.get('api/transform/checkfirst/' + this.discountForm.applicantId);
						if (res.code === 200) {
							isfirst = (res.total==0);
						} else {
							this.$message.error(res.message);
							return
						}
					} catch (e) {
						this.$message.error('服务项目请求出错！', e.message);
						return
					}

					if (this.serviceForm.service.length ==0) {
						this.$message.error('请在办理业务中添加服务项目');
						this.tabvalue = 'business'
						return;
					} else if (isfirst==false && this.discountForm.type=='首单特惠') {
						this.$message.error('申请人已经签过单，无法享有首单特惠。请更改优惠单类型！');
						this.tabvalue = 'base'
						return;
					} else {
						this.discountForm.recs = deepCopy(this.serviceForm.service)
					}
					
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {			
						// 申请
						let res = await axios.post('api/discountform/add', this.discountForm);
						if (res.code === 200) {
							this.$message.success(res.message);
							this.query();
							this.dialogFormVisible = false
						} else {
							this.$message.error(res.message);
						}
					} catch (e) {
						this.$message.error('申请出错！', e.message);
					}
				//关闭加载框
				loading.close();	 
				

				} else {
				}
			})

		},
		// 添加服务
		addService() {
			this.action = "adddetail";
			this.dialogserviceFormDetailVisible = true
			this.serviceFormDetail.id = 0
			this.serviceFormDetail.serviceId = 0
			this.serviceFormDetail.name = ""
			this.serviceFormDetail.amount = 0
			this.serviceFormDetail.unit = ""
			this.serviceFormDetail.priceb = 0
			this.serviceFormDetail.price = 0
			this.serviceFormDetail.pricea = 0
			this.serviceFormDetail.memo = ""
			this.serviceFormDetail.service = []
		},
		// 编辑服务
		editService(index, row) {
			this.action = "editdetail"
			this.dindex = index;
			this.dialogserviceFormDetailVisible = true
			this.serviceFormDetail = deepCopy(row)
		},
		// 删除服务
		delService(index, row) {
			this.serviceForm.service.splice(index, 1)
		},
		// 服务项目变化时
		async servicechange(id) {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				console.log(id)
				let res = await axios.get('api/servicedetail/get/' + id);
				if (res.code === 200) {
					this.serviceFormDetail.service = res.data;
					if (this.serviceFormDetail.service.length > 0) {
						this.serviceFormDetail.amount = this.serviceFormDetail.service[0].number
						this.serviceFormDetail.serviceId = id
						this.serviceFormDetail.id = this.serviceFormDetail.service[0].id
						this.serviceFormDetail.name = this.serviceFormDetail.service[0].name
						this.serviceFormDetail.price = this.serviceFormDetail.service[0].price
						this.serviceFormDetail.priceb = this.serviceFormDetail.service[0].price
						this.serviceFormDetail.unit = this.serviceFormDetail.service[0].unit
						this.serviceFormDetail.spec = this.serviceFormDetail.service[0].spec
						this.serviceFormDetail.type = this.serviceFormDetail.service[0].type

						this.serviceFormDetail.pricea = this.serviceFormDetail.service[0].price
						this.serviceFormDetail.items = this.serviceFormDetail.service[0].items
						this.serviceFormDetail.memo = this.serviceFormDetail.service[0].memo
					} 
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('服务项目请求出错！', e.message);
			}
			console.log(this.serviceFormDetail)
			// 关闭加载框
			loading.close();
		},
		// 确认添加，编辑服务信息
		confirmService() {
			this.$refs.serviceFormDetail.validate(async valid => {
				if (valid) {
					let res = null;
					if (this.action == "adddetail") {
						// 添加服务
						this.serviceForm.service.push(deepCopy(this.serviceFormDetail))
						
					} else if (this.action == "editdetail") {
						// 编辑服务
						this.serviceForm.service[this.dindex].name = this.serviceFormDetail.name
						this.serviceForm.service[this.dindex].amount = this.serviceFormDetail.amount
						this.serviceForm.service[this.dindex].unit = this.serviceFormDetail.unit
						this.serviceForm.service[this.dindex].priceb = this.serviceFormDetail.priceb
						this.serviceForm.service[this.dindex].price = this.serviceFormDetail.price
						this.serviceForm.service[this.dindex].pricea = this.serviceFormDetail.pricea
					}
					console.log(this.serviceForm)
					sum = 0
					for (let row of this.serviceForm.service) {
						sum = sum + parseInt(row.totalprice)
					}
					this.discountForm.price = sum
					this.dialogserviceFormDetailVisible = false
				} else {

				}
			})
		},
		//审核
		audit(index, row) {
			this.action = "edit"
			this.index = index;
			this.dialogFormVisible = true;
			this.discountForm = deepCopy(row)
		},
		//作废
		async removediscount(){
			try {
				this.discountForm.userid = localStorage.getItem('USERID');
				let res =await axios.put('api/discount/remove', this.discountForm);
				console.log(res)
				if (res.code === 200) {
					this.query();
					this.$message({
					  type: 'success',
					  message: '作废成功!'
					});
				} else {
					this.$message.error(res.message);
				}
			
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
		},
		//删除
		remove(index, row) {
			this.$confirm('此操作将作废优惠信息, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.discountForm = deepCopy(row)
				this.removediscount()
		
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消作废'
				});
			});
		},
		// 显示侧边栏
		showLeftBar() {

			if (this.leftbar_show)
				return this.leftbar_show = false
			if (!this.leftbar_show)
				return this.leftbar_show = true

		},
		// 表格多选 
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},


		// 检查数据是否有修改
		checkDataChanged() {
			// 比对数据有无发生变化
			for (let key in this.testpaperForm) {
				if (this.testpaperForm[key] != this.testpaperFormOrg[key]) {
					return true;
				}
			}
			return false;
		},

		start() {
			this.queryForm.pageNo = 1
			this.query()
		},
		// 查询
		async query() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/discountlist/querylist', this.queryForm);
				console.log(res)
				if (res.code === 200) {
					this.pagedata = res.data;
					this.pagetotal = res.total;
					this.$message.success(res.message);
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},
		// 驳回
		async nopass() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				this.$confirm('确定要驳回当前优惠单吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					// 驳回
					this.discountForm.userid = localStorage.getItem('USERID');
					let res = await axios.put('api/discountform/nopass', this.discountForm);
					if (res.code === 200) {
						this.query();
						this.dialogFormVisible = false
						this.$message.success(res.message);
					} else {
						this.$message.error(res.message);
					}
				}).catch((e) => {
					if (e.message) this.Msg('error', e.message);
				});
			} catch (e) {
				this.$message.error('驳回出错！', e.message);
			}
			// 关闭加载框
			loading.close();

		},

		// 审核通过
		async confirm(index, row) {

			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {

				this.$confirm('请确认优惠单信息是否正确，然后点击确定通过审核。', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					// 审核
					this.discountForm.userid = localStorage.getItem('USERID');
					this.discountForm = deepCopy(row);
					this.discountForm.userid= localStorage.getItem('USERID');
					let res = await axios.put('api/discountform/audit', this.discountForm);
					if (res.code === 200) {
						this.$message.success(res.message);
						this.query();
						this.dialogFormVisible = false
					} else {
						this.$message.error(res.message);
					}
				}).catch((e) => {
					if (e.message) this.Msg('error', e.message);
				});

			} catch (e) {
				this.$message.error('审核出错！', e.message);
			}
			// 关闭加载框
			loading.close();

		},
		// 是否显示审核
		showAudit(index, row) {
			console.log(row)
			if (row.leaderId == localStorage.getItem('USERID') && row.leaderstatus == row.leader + '[' + "待审核" + ']') {
				return true;
			} else if (row.managerId == localStorage.getItem('USERID') && row.managerstatus == row.manager + '[' + "待审核" + ']') {
				return true;
			} else {
				return false;
			}
		},


		selectionChange(selection) {
			this.selection = selection
		},



		// 设定表格当前页
		handleCurrentPageChange(selectedPageNo) {
			this.queryForm.pageNo = selectedPageNo
			// 加载数据页
			this.query()
		},
		//设定每页记录数
		handleSizeChange(val) {
			this.queryForm.pagesize = val
			// 加载数据页
			this.query()
		},
		// 设定表格当前页
		handlePersonCurrentPageChange(selectedPageNo) {
			this.queryPersonForm.pageNo = selectedPageNo
			// 加载数据页
			this.queryPerson()
		},
		//设定每页记录数
		handlePersonSizeChange(val) {
			this.queryPersonForm.pagesize = val
			// 加载数据页
			this.queryPerson()
		},
		// 取得所有服务项目
		async getService() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/service/get');
				if (res.code === 200) {
					this.services = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('服务项目请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},
		serviceDetailClick(row, column, event) {
			this.serviceFormDetail.id = row.id
			this.serviceFormDetail.amount = row.number
			this.serviceFormDetail.name = row.name
			this.serviceFormDetail.price = row.price
			this.serviceFormDetail.unit = row.unit
			this.serviceFormDetail.spec = row.spec
			this.serviceFormDetail.type = row.type
			this.serviceFormDetail.priceb = row.price
			this.serviceFormDetail.pricea = row.price
			this.serviceFormDetail.items = row.items
			this.serviceFormDetail.memo = row.memo
			console.log(this.serviceFormDetail)
		},
	},

	async mounted() {
		// 自动调整表格高度
		window.onresize = () => {
				return (() => {
					this.tableHeight = window.innerHeight - 180
				})()
			},
			//初始化服务名称
			this.initServiceName();
		//初始化用户列表
		this.getAllUser();
		// 取得服务列表
		this.getService();
		// 取得我的客户公司名称
		this.getCompany();
	}
});
